package com.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.fhMall.response.UmsMemberResponse;
import com.wechat.core.constant.Constant;
import com.wechat.core.constant.enums.support.RStatus;
import com.wechat.core.exception.ServiceException;
import com.wechat.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Auther:
 */
public class BaseController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${spring.redis.tokenTimeout}")
    private int timeout;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public UmsMemberResponse getWechatUserInfo(String userId){
        UmsMemberResponse wechatUser = JSONObject.parseObject(redisTemplate.opsForValue().get(Constant.WECHAT_USER_ID+ userId), UmsMemberResponse.class);
        if (wechatUser == null) {
            throw new ServiceException("请重新登陆", RStatus.NO_LOGIN);
        }
        return wechatUser;
    }

    public UmsMemberResponse updateWechatUserInfo(UmsMemberResponse wechatUser){
        redisTemplate.opsForValue().set(Constant.WECHAT_USER_ID + wechatUser.getId(), JSONObject.toJSONString(wechatUser), timeout);
        return wechatUser;
    }


    public Integer getUserId(){
        return ((Integer)this.getHttpServletRequest().getAttribute("userId"));
    }

    public String getOpenId(){
        return (String)this.getHttpServletRequest().getAttribute("openId");
    }

    public String getToken(){
        return (String)this.getHttpServletRequest().getAttribute("token");
    }

    private HttpServletRequest getHttpServletRequest(){
        return  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

}
